<?php
/**
 * Created by PhpStorm.
 * Author: sitenv@aliyun.com
 * CreateTime: 2021/07/12 17:52
 * Blog：www.myblogs.xyz
 */

namespace app\common\service;


use app\common\model\Setting;

class SendService
{
    public static function verifyCode($mobile, $code)
    {
        if (is_mobile($mobile)){
            $content = "您的验证码是：" . $code . "。请不要把验证码泄露给其他人。";
            $rows = self::sms($mobile, $content, true);
            if($rows) {
                return true;
            }
        }
        return false;
    }
    /**
     * 发送短信
     * @param int $mobile 手机号
     * @param string $content 短信内容
     * @param bool $is_success 短信内容
     * @param int $send_type 短信类型
     * @return bool
     */
    protected static function sms($mobile, $content, $is_success = false, $send_type = 1)
    {
        $setting_model = new Setting();
        $setting_data = $setting_model->settingFind('sms');
        // 阿里短信
        if ($setting_data['send_mode'] == 0){

        }
        // 互亿短信
        if ($setting_data['send_mode'] == 1){
            $app_secret = $setting_data['hy'];
            $post_data = "account=" . $app_secret['app_key'] . "&password=" . $app_secret['secret_key'] . "&mobile=" . $mobile . "&content=" . rawurlencode($content);
            $target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
            if ($is_success){
                $gets =  self::xml_to_array(self::post($post_data, $target));
                if($gets['SubmitResult']['code'] != 2) {
                    return false;
                }
            }
        }
        // 聚合短信
        if ($setting_data['send_mode'] == 2){
            $app_secret = $setting_data['jh'];
            header('content-type:text/html;charset=utf-8');
            $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
            $smsConf = array(
                'key'   => $app_secret['app_key'], //您申请的APPKEY
                'mobile'    => $mobile, //接受短信的用户手机号码
                'tpl_id'    => $app_secret['tpl_id'], //您申请的短信模板ID，根据实际情况修改
                'tpl_value' =>'#code#=' . $content //您设置的模板变量，根据实际情况修改
            );
            //请求发送短信
            $result = self::juhecurl($sendUrl, $smsConf, 1);
            if ($is_success){
                if($result){
                    $json_data = json_decode($result, true);
                    $error_code = $json_data['error_code'];
                    if($error_code != 0){
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public static function email($email, $username, $title, $body)
    {
        // 获取邮箱配置服务
        $setting_model = new Setting();
        $setting_data = $setting_model->settingFind('email');

        import('phpmailer.phpmailer');
        import('phpmailer.smtp');
        $mail = new \PHPMailer();
        $mail->isSMTP();
        $mail->CharSet = 'utf-8';
        // Specify main and backup SMTP servers
        $mail->Host = $setting_data['smtp'];
        // Enable SMTP authentication
        $mail->SMTPAuth = true;
        // SMTP username
        $mail->Username = $setting_data['email_address'];
        // SMTP password
        $mail->Password = $setting_data['email_password'];
        //$mail->Password = '';
        // tls or ssl
        if ($setting_data['is_ssl']){
            $mail->SMTPSecure = 'ssl';
        }
        $mail->Port = $setting_data['port'];
        $mail->setFrom($setting_data['send_email'], $setting_data['send_name']);
        // Add a recipient
        $mail->addAddress($email, $username);
        $mail->Subject = $title;
        if ($body instanceof \Closure) {
            $body = $body();
        }
        $mail->msgHTML($body);

        return $mail->send();
    }

    protected static function post($curlPost, $url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }

    //将xml数据转换为数组格式。
    protected static function xml_to_array($xml)
    {
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if(preg_match_all($reg, $xml, $matches)){
            $count = count($matches[0]);
            for($i = 0; $i < $count; $i++){
                $subxml= $matches[2][$i];
                $key = $matches[1][$i];
                if(preg_match( $reg,$subxml )){
                    $arr[$key] = self::xml_to_array($subxml);
                }else{
                    $arr[$key] = $subxml;
                }
            }
        }
        return $arr;
    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    public static function juhecurl($url, $params=false, $ispost=0)
    {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if($ispost)
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }
}